package com.hzsoft.sys.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.hzsoft.base.entity.BJuiJSON;
import com.hzsoft.base.entity.Page;
import com.hzsoft.sys.entity.SysMenu;
import com.hzsoft.sys.entity.SysRole;
import com.hzsoft.sys.entity.SysRoleMenu;
import com.hzsoft.sys.service.SysMenuService;
import com.hzsoft.sys.service.SysRoleMenuService;
import com.hzsoft.sys.service.SysRoleService;
import com.hzsoft.util.StrUtil;

@Controller
@RequestMapping("/system/role")
public class SysRoleController extends com.hzsoft.base.BaseController{
	
	@Autowired
	SysRoleService roleService;
	@Autowired
	SysMenuService menuService;
	@Autowired
	SysRoleMenuService roleMenuService;
	
	@Autowired
	private TransactionDefinition txDefinition;
	@Autowired
	private PlatformTransactionManager txManager;
	
	@RequestMapping("/systemRoleList")
	public ModelAndView listRole(@ModelAttribute SysRole role,Model model,HttpServletRequest request,HttpServletResponse response){
		
		// 分页设置
		String pageCurrent = request.getParameter("pageCurrent");
		Page page = new Page();
		if (StringUtils.isNotBlank(pageCurrent)) {
			page.setPageCurrent(Integer.parseInt(pageCurrent));
			role.setPage(page);
		}
		
		if(role.getName() == null){
			role.setName("");
		}
		role.setName(role.getName().trim());
		List<SysRole> list = roleService.listPageRole(role);
		
		model.addAttribute("role",role);
		model.addAttribute("page", role.getPage());
		model.addAttribute("list",list);
		
		return new ModelAndView("/system/role/roleList");
	}
	
	/**
	 * 弹出添加页面
	 * @param menu
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddRole")
	public ModelAndView toAddRole(@ModelAttribute SysRole role,HttpServletResponse response, HttpServletRequest request){
		ModelAndView model = new ModelAndView();
	
		model.setViewName("/system/role/addRole");
		return model;
	}
	/**
	 * 设置权限
	 * @param role
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping("/toSetPermessions")
	public ModelAndView toSetPermessions(@ModelAttribute SysRole role,HttpServletResponse response, HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		//取所有的menu
		List<SysMenu> menuList = menuService.selectAllMenu();
		//取当前角色已有的menu
		List<SysRoleMenu> roleMenuList =  roleMenuService.selectByRoleId(role.getRoleId());
				
		for(SysMenu menu:menuList){
			for(SysRoleMenu rm:roleMenuList){
				if(menu.getId().equals(rm.getId())){
					menu.setChecked("true");
				}
			}
		}
		mv.addObject("menuList2",menuList);
		mv.addObject("roleId",role.getRoleId());
		
		mv.setViewName("/system/role/setPermessions");
		return mv;
	}
	
	/**
	 * 暂时不用
	 * @param roleId
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/ajaxTree")
	public void ajaxTree(String roleId,HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		//取所有的menu
		List<SysMenu> menuList = menuService.selectAllMenu();
		//取当前角色已有的menu
		List<SysRoleMenu> roleMenuList =  roleMenuService.selectByRoleId(roleId);
				
		for(SysMenu menu:menuList){
			for(SysRoleMenu rm:roleMenuList){
				if(menu.getId().equals(rm.getId())){
					menu.setChecked("true");
				}
			}
		}
		out.print(JSON.toJSONString(menuList));
	}
	
	/**
	 * 设置权限、查看权限
	 * @param record
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/setPermessions")
	public ModelAndView setPermessions(@ModelAttribute SysRoleMenu record,String roleId,HttpServletRequest request,HttpServletResponse response){
		TransactionStatus status = txManager.getTransaction(txDefinition);
		ModelAndView mv=new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		String str = request.getParameter("v");//原始字符串
		StrUtil.funsplit(str);//转成数组

		List<String> list = new ArrayList<String>();
		for(int i=0;i<StrUtil.funsplit(str).length;i++){
			if(!"".equals(StrUtil.funsplit(str)[i].trim())){
			list.add(StrUtil.funsplit(str)[i]);
			}
		}
		
//		List list = Arrays.asList(StrUtil.funsplit(str));	
		try {
			if(record!=null)
				roleMenuService.deleteByRoleId(roleId);	//先删除角色的菜单
			if(null != list){
				List<SysRoleMenu> roleMenuList = new ArrayList<SysRoleMenu>();
				for(int i = 0; i < list.size(); i++){
					SysRoleMenu roleMenu = new SysRoleMenu();
					roleMenu.setRoleId(roleId);
					roleMenu.setMenuId((String) list.get(i));
					roleMenuList.add(roleMenu);
				}
				roleMenuService.insert(roleMenuList);
				
				
				bjui.setStatusCode("200");
				bjui.setMessage("设置成功！！！");
				bjui.setTabid("navtab-role");
				bjui.setCloseCurrent(true);
				txManager.commit(status);
			}else{
				bjui.setStatusCode("300");
				bjui.setMessage("请为岗位设置可以操作的权限！");
			}
		}catch (Exception e) {
			txManager.rollback(status);
			e.printStackTrace();				
			bjui.setStatusCode("300");
			bjui.setMessage("设置失败！！！");
		}
		
		String msg = JSONObject.fromObject(bjui).toString();
		
		mv.addObject("msg", msg);
		mv.setViewName("/msg");
		return mv;
	}
	
	/**
	 * 功能设置：添加
	 */
	@RequestMapping(value = "/addRole")	
	public ModelAndView addMenu(SysRole record,HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv=new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		
		try {
			roleService.insertSelective(record);
			
			bjui.setStatusCode("200");
			bjui.setMessage("添加成功！！！");
			bjui.setTabid("navtab-role");
			bjui.setCloseCurrent(true);
		} catch (Exception e) {
			e.printStackTrace();
			bjui.setStatusCode("300");
			bjui.setMessage("添加失败！！！");
		}
		
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}
	
	
	/**
	 * 功能设置：删除
	 */
	@RequestMapping(value = "/deleteRole")
	public ModelAndView deleteRole(@ModelAttribute SysRole role,HttpServletRequest request,HttpServletResponse response) throws IOException{
		BJuiJSON bjui = new BJuiJSON();
		ModelAndView mv = new ModelAndView();

		try {
			// menuService.deleteAll(user);

			roleService.deleteByPrimaryKey(role.getRoleId());

			bjui.setStatusCode("200");
			bjui.setMessage("删除成功！！！");
			bjui.setTabid("navtab-role");
		} catch (Exception e) {
			e.printStackTrace();
			bjui.setStatusCode("300");
			bjui.setMessage("删除失败！！！");
		}

		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}
	
	/**
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/toUpdateRole")
	public ModelAndView toUpdateMenu(SysRole role){
		ModelAndView mv = new ModelAndView();
		mv.addObject("role", roleService.selectByPrimaryKey(role.getRoleId()));
		mv.setViewName("/system/role/updateRole");
		return mv;
	}
	
	/**
	 */
	@RequestMapping(value="/updateRole",method=RequestMethod.POST)
	public ModelAndView updateRole(SysRole role,HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv = new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		try {
			roleService.updateByPrimaryKeySelective(role);

			bjui.setStatusCode("200");
			bjui.setMessage("更新成功！！！");
			bjui.setTabid("navtab-role");
			bjui.setCloseCurrent(true);

		} catch (Exception e) {
			bjui.setStatusCode("300");
			bjui.setMessage("更新失败！！！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg",msg);
		mv.setViewName("msg");
		return mv;
	}
	
	
	/*
	 * ajax判断roleID是否重复
	 */
	@RequestMapping("/ajaxJudgeUserId")
	public void ajaxJudgeUserId(String roleId,HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		int data=1;
		if(roleService.selectByPrimaryKey(roleId)!=null){
			data=0;
		}
		out.print(data);
	}
}